{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "source": [
    "\n",
    "# Introduction to input-output analysis using Python\n",
    "\n",
    "Author: <a href=\"mailto:a.owen@leeds.ac.uk\"> Dr Anne Owen </a> \n",
    "\n",
    "The general structure of an input-output table is:\n",
    "\n",
    "\n",
    "<img src=\"https://user-images.githubusercontent.com/24877051/146377849-723d8122-7e2a-4d0b-b45c-f8351c4fcbb8.png\" width=400 height=400 />\n",
    "\n",
    "\n",
    "Consider this very simple model of the economies of <a href=\"https://parksandrecreation.fandom.com/wiki/Pawnee,_Indiana\"> the town of Pawnee</a> and <a href=\"https://parksandrecreation.fandom.com/wiki/Eagleton,_Indiana\"> the town of Eagleton</a><sup>*</sup>:\n",
    "\n",
    "<img src=\"https://github.com/earao/images/blob/main/Picture%201.png?raw=true\" width=600 height=470 />\n",
    "\n",
    "We are going to use the above data to find the GHG emissions for:\n",
    "\n",
    "<ul>\n",
    "  <li>Eagleton's Production</li>\n",
    "  <li>Pawnee's Production</li>\n",
    "  <li>Eagleton's Consumption</li>\n",
    "  <li>Pawnee's Consumption</li>\n",
    "</ul>\n",
    "\n",
    "\n",
    "But, before we start, paste the following into the box below:\n",
    "\n",
    "```python\n",
    "import matplotlib as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n",
    "%precision 2\n",
    "```\n",
    "\n",
    "<sup>*</sup>Knowledge of <a href=\"https://parksandrecreation.fandom.com/wiki/Main_Page\"> the TV show Parks & Recreation</a> not required for this module"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1. Constructing the dataset in Python\n",
    "\n",
    "## Exercise 1.1: Make arrays for Z,Y and f\n",
    "\n",
    "In Python use the following code to make the array $\\textbf{Z}$\n",
    "\n",
    "```python\n",
    "Z_data = np.array([[660,10,2,30,1,1],\n",
    "                   [300,500,100,20,30,20],\n",
    "                   [200,400,300,10,30,100],\n",
    "                   [40,2,1,440,20,2],\n",
    "                   [20,200,200,140,400,90],\n",
    "                   [10,30,200,200,200,200]])\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Use the same format to make $\\textbf{Y}$ and call the variable ```Y_data```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and make $\\textbf{f}$, calling the variable ```f_data```. Remember that the format for making a row vector is ```np.array([[number, number, number]])``` with TWO sets of square brackets!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are going to make use of the Pandas library in Python. Pandas is excellent for handling databases. We are going to turn our array data into dataframes which can include the row and column headings. We can also use more calculation properties available with dataframes.\n",
    "\n",
    "## Exercise 1.2: Make heading files\n",
    "\n",
    "Copy the following into the box below:\n",
    "\n",
    "```python\n",
    "sectors = ['Eagleton Food',\n",
    "           'Eagleton Machines',\n",
    "           'Eagleton Energy',\n",
    "           'Pawnee Food',\n",
    "           'Pawnee Machines',\n",
    "           'Pawnee Energy']\n",
    "```\n",
    " \n",
    " to make a heading file for the columns and rows of $\\textbf{Z}$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now make another heading file called 'final_demand' which contains the headings 'Eagleton Final Demand' and 'Pawnee Final Demand'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 1.3: Make dataframes for Z,Y and f\n",
    "\n",
    "We are going to use the pandas DataFrame function to convert our data into a more useful format.\n",
    "\n",
    "If you take a look at the notation for this function (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) it says:\n",
    "\n",
    "class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)\n",
    "\n",
    "Try\n",
    "\n",
    "```python\n",
    "Z = pd.DataFrame(Z_data, index=sectors, columns=sectors)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are telling Python to make a dataframe, where the data is ```Z_data```, the index (the row headings) is ```sectors``` and the columns is ```sectors```\n",
    "\n",
    "Use this format to make ```Y``` the dataframe for final demand data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Paste the following in to the box below to make a dataframes for  ```f```\n",
    "\n",
    "```f = pd.DataFrame(f_data, columns=sectors)```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Dont worry about the zero as the index here - it doesn't really matter.\n",
    "\n",
    "## Exercise 1.4: Referring to DataFrame items\n",
    "\n",
    "When we worked with arrays, we could write ```Z_data[2,3]``` to refer to the item in the 3rd row down and 4th column accross (remember Python counts from zero). This value represents the monetary inputs of Eagleton's Energy to making a Pawnee Food product.\n",
    "\n",
    "With DataFrames we write:\n",
    "```python\n",
    "Z.iloc[2,3]\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that ```iloc``` refers to a numerical position.\n",
    "\n",
    "We can also use the headings to refer to a cell. \n",
    "\n",
    "Try \n",
    "```python\n",
    "Z.loc['Eagleton Energy','Pawnee Food']\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that ```loc``` refers to a position by name.\n",
    "\n",
    "Now if you wanted to extract the complete data of where Eagleton's energy goes to (the Pawnee energy row), you can use:\n",
    "```python\n",
    "Z.loc['Eagleton Energy']\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To extract the column of data showing inputs to Pawnee's Food (the production recipe of Pawnee's food), you can use:\n",
    "```python\n",
    "Z['Pawnee Food']\n",
    "```\n",
    "\n",
    "Extracting or referring to columns does not require ```loc```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 1.5: Make a vector of total output x\n",
    "\n",
    "Calculate the column vector of total output. You will need to sum along the rows of both $\\textbf{Z}$ and $\\textbf{Y}$. We can use ```np.sum('data','dimension')```. Call your variable $\\textbf{x}$\n",
    "\n",
    "Try \n",
    "```python\n",
    "x = np.sum(Z,1) + np.sum(Y,1)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Scroll back up to the top to check that you have the correct total output figures from the original table.\n",
    "\n",
    "Lets make it neat by putting it in a dataframe:\n",
    "\n",
    "```x = pd.DataFrame(x,index=sectors)```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that we can use the numpy function 'sum' with DataFrames. The result $\\textbf{x}$ keeps the row headings because it has checked that both $\\textbf{Z}$ and $\\textbf{Y}$ contain the same sectors\n",
    "\n",
    "In input-output analysis the sum of the rows is the same as the sum of the columns so we could have added the columns of $\\textbf{Z}$ to the value added data. It is best practise to sum along $\\textbf{Z}$ and $\\textbf{Y}$ however becuase sometimes IO tables do not balance and this data is considered more accurate.\n",
    "\n",
    "## Exercise 1.6: Finding total production emissions in Eagleton and Pawnee\n",
    "\n",
    "Can you calculate the total production emissions for Eagleton?\n",
    "\n",
    "The emissions are held in the emissions vector $\\textbf{f}$ and we can either sum the emissions by referring to their position in the vector or by naming the start and end sectors. Here we describe selecting all the rows and the columns between the appropriate headings\n",
    "\n",
    "Try \n",
    "```python\n",
    "eagleton_production = np.sum(f.loc[:,'Eagleton Food':'Eagleton Energy'], 1)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or, we can  refering to the locations in numeric form. Python starts to count from zero and to refer to a range of cells, you tell Python the start cell and cell after the one you want to end on.\n",
    "\n",
    "So we would write:\n",
    "\n",
    "```python\n",
    "eagleton_production = np.sum(f.iloc[:,0:3],1)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Find the sum of Pawnee's production emissions by referring to the cell labels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now try and use the cell locations in numeric form:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2. Make the A matrix \n",
    "\n",
    "Now, we want to calculate the emissions from consumption rather than production. This means that we need to be able to calculate emissions $\\textbf{f}$ as a function of final demand $\\textbf{Y}$.\n",
    "\n",
    "We start by formulating output $\\textbf{x}$ as a function of final demand $\\textbf{Y}$.\n",
    "\n",
    "We know that $\\textbf{x}$ = $\\textbf{Z}$+$\\textbf{Y}$\n",
    "\n",
    "Which, for a general row $i$ in our matrix, can be written:\n",
    "\n",
    "$x_i$ = $z_{i1}$ + $z_{i2}$ + $z_{i3}$ + $z_{i4}$ + $z_{i5}$ + $z_{i6}$ + $y_{i1}$ + $y_{i2}$ \n",
    "\n",
    "Now we produce a matrix $\\textbf{A}$ which shows the contribution each element in $\\textbf{Z}$ makes towards total output $\\textbf{x}$. Essentially this means dividing each column in $\\textbf{Z}$ by the matching element in $\\textbf{x}$.\n",
    "\n",
    "Now:\n",
    "\n",
    "$a_{ij}$ = $\\frac{z_{ij}}{x_j}$\n",
    "\n",
    "So we can write:\n",
    "\n",
    "$x_i$ = $a_{i1}{x_1}$ + $a_{i2}{x_2}$ + $a_{i3}{x_3}$ + $a_{i4}{x_4}$ + $a_{i5}{x_5}$ + $a_{i6}{x_6}$ + $y_{i1}$ + $y_{i2}$ \n",
    "\n",
    "and so\n",
    "\n",
    "$\\textbf{x}$ = $\\textbf{Ax}$+$\\textbf{Y}$\n",
    "\n",
    "$\\textbf{Y}$ = $\\textbf{x}$ - $\\textbf{Ax}$ \n",
    "\n",
    "$\\textbf{x}$ = $(\\textbf{I}$ - $\\textbf{A})^{-1}$ $\\textbf{Y}$\n",
    "\n",
    "or\n",
    "\n",
    "$\\textbf{x}$ = $\\textbf{L}\\textbf{Y}$\n",
    "\n",
    "$\\textbf{L}$ is known as the Leontief inverse and helps us to express output of industry as a function of demand on products. It essentially redistributes output by industry to final demand by product.\n",
    "\n",
    "In order to calculate $\\textbf{L}$ we first have to make $\\textbf{A}$.\n",
    "\n",
    "In Python, the easiest way to do this is an element-wise division where each cell in $\\textbf{Z}$ is divided by a second matrix, which has the same dimensions (size) as $\\textbf{Z}$ but contains $\\textbf{x}$ in row form, repeated down each row.\n",
    "\n",
    "We are going to call this second matrix ```big_X```\n",
    "\n",
    "## Exercise 2.1: Make big_X\n",
    "\n",
    "Try \n",
    "```python\n",
    "big_X = np.tile(np.transpose(x),[6,1])\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Can you see how this formula works?\n",
    "\n",
    "We have tranposed $\\textbf{x}$ to make it a row vector, then repeated this 6 times down and once across. We won't turn this into a DataFrame because it is an intermediate step and the row headings would not make sense.\n",
    "\n",
    "## Exercise 2.2: Make A\n",
    "\n",
    "Now try \n",
    "```python\n",
    "A = Z/big_X\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that every cell in $\\textbf{A}$ is a number smaller than one. Python is writing these numbers in standard form.\n",
    "\n",
    "The first cell should be '4.54e-01' or 0.454.\n",
    "\n",
    "# 3. Calculating L - the Leontief inverse\n",
    "\n",
    "Leontief's equation is $L = (I-A)^{-1}$\n",
    "\n",
    "## Exercise 3.1: Make the identity matrix I\n",
    "\n",
    "Look back at the matrix algebra workbook and make an identity matrix $\\textbf{I}$ which is 6 cells wide and long"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 3.2: Make L\n",
    "\n",
    "Now try to make $\\textbf{L}$ using Python's ```np.linalg.inv``` function that we also saw in the homework"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should have got a result that looks like this:\n",
    "\n",
    "```python\n",
    "array([[ 1.85,  0.03,  0.01,  0.07,  0.01,  0.  ],\n",
    "       [ 0.69,  1.69,  0.18,  0.09,  0.07,  0.06],\n",
    "       [ 0.61,  0.67,  1.39,  0.11,  0.1 ,  0.16],\n",
    "       [ 0.09,  0.02,  0.01,  1.53,  0.04,  0.01],\n",
    "       [ 0.34,  0.52,  0.36,  0.32,  1.5 ,  0.18],\n",
    "       [ 0.22,  0.26,  0.31,  0.36,  0.29,  1.26]])```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 4. Calculating the consumption emissions for Eagleton and Pawnee\n",
    "\n",
    "Now let $\\textbf{e}$ be a vector of emissions intensity - the tonnes of $CO_2$ per unit of output.\n",
    "\n",
    "$\\textbf{e = fx}^{-1}$\n",
    "\n",
    "multiplying both sides of the Leontief equation by $\\textbf{e}$ gives:\n",
    "\n",
    "$\\textbf{ex} = \\textbf{eLY}$\n",
    "\n",
    "which simplifies to:\n",
    "\n",
    "$\\textbf{f} = \\textbf{eLY}$\n",
    "\n",
    "total emissions can be formulated by the product of emissions intensity, the Leontief inverse and final demand. We have emissions as a function of final demand!\n",
    "\n",
    "We are going to reserve $\\textbf{f}$ for the production vector and use $\\textbf{q}$ for consumption emissions.\n",
    "\n",
    "## Exercise 4.1: Calculating e\n",
    "\n",
    "We cannot  use ```e = f/x``` here because $\\textbf{f}$ is a row vector and $\\textbf{x}$ is a column vector. For this project, we want $\\textbf{e}$ to be a row vector so we must first transpose $\\textbf{x}$. Try:\n",
    "\n",
    "```python\n",
    "e = f/np.transpose(x)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Lets make a barchart of e. Try:\n",
    "\n",
    "```python\n",
    "chart = e.plot(kind='bar')\n",
    "chart.set_ylabel('tonnes CO2 per £')\n",
    "```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 4.2: Calculating eL\n",
    "\n",
    "Try ```eL = np.dot(e, L)```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we want to make a bar chart similar to the one above but for eL we need eL to be a dataframe. But when we use eL for later calculations it needs to stay as an array. Try:\n",
    "\n",
    "```python\n",
    "eLdataframe = pd.DataFrame(eL,columns=sectors)\n",
    "chart = eLdataframe.plot( kind = 'bar')\n",
    "chart.set_ylabel('tonnes CO2 per £')\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's think a bit more about what $\\textbf{eL}$ represents. We have multiplied emissions intensity of <b>industries</b> by the matrix which translates industry inputs to products. \n",
    "\n",
    "$\\textbf{eL}$ is therefore the emissions intensity of <b>products</b>\n",
    "\n",
    "Each number represents the full supply chain emissions per unit spend of a product.\n",
    "\n",
    "Compare the figures you have for the emissions intensity of an industry with the corresponding product emissions intensity. You should find that they are larger because we are taking account of the full supply chain of production.\n",
    "\n",
    "Observe that for food, the product emissions intensity is now larger than the product emissions intensity for energy. This is because we are including emissions from highly polluting sectors like energy in the supply chain of a less intensive product like food."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 4.3: Calculating Total town level footprints\n",
    "\n",
    "$\\textbf{q = eLY}$. \n",
    "\n",
    "We calculated ```eL``` in the previous exercise. Now we need to multiply it by ```Y```. \n",
    "\n",
    "Try ```q = np.dot(eL, Y)```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should find that you have a result matrix of dimension [$1$,$2$]. But what do the numbers mean?\n",
    "\n",
    "Lets look at the dimensions of $\\textbf{e}$, $\\textbf{L}$ and $\\textbf{Y}$:\n",
    "\n",
    "[$1$,$6$]  [$6$,$6$]  [$6$,$2$]\n",
    "\n",
    "The final result is the emissions by final demand region [$1$,$2$] where the $1$ is from the emissions intensity vector $\\textbf{e}$  and the $2$ is from the final demand matrix $\\textbf{Y}$. So the emissions from Eagleton's consumption are 4443.62 tonnes $CO2$ or the carbon footprint of Eagleton is 4443.62 tonnes $CO2$.\n",
    "\n",
    "If this reasoning is correct, total emissions should be preserved. Can you check if the sum of the production emissions $\\textbf{f}$ is the same as the sum of the consumption emissions $\\textbf{q}$ that you have just calculated?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can make your result into a neat DataFrame like this: \n",
    "\n",
    "```total_country_footprints = pd.DataFrame(q,columns=final_demand)```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 4.4: Calculating product level footprints\n",
    "\n",
    "If we wanted to breakdown the footprint of each country by product we would need to be pre-multiplying $\\textbf{Y}$ by something with 6 product rows rather than the 1 row from eL that we used in Excercise 4.2.\n",
    "\n",
    "If we diagonalise $\\textbf{eL}$, we will make a matrix of products by products. The multiplying this by $\\textbf{Y}$ gives 'products by regions'\n",
    "\n",
    "Try multiplying a diagonalised $\\textbf{eL}$ by $\\textbf{Y}$ to make ```country_footprints_by_product```.\n",
    "\n",
    "Use the function ```np.diagflat(eL)``` then multiply by $\\textbf{Y}$:\n",
    "\n",
    "```python\n",
    "country_footprints_by_product = np.dot(np.diagflat(eL), Y)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Make your result into a DataFrame called ```country_footprints_by_product```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " Try:\n",
    "\n",
    "```python\n",
    "chart = country_footprints_by_product.plot(kind='bar')\n",
    "chart.set_ylabel('tonnes CO2 per £')\n",
    "```\n",
    "\n",
    "and\n",
    "\n",
    "```python\n",
    "chart = country_footprints_by_product.plot(kind='bar', stacked=True)\n",
    "chart.set_ylabel('tonnes CO2 per £')\n",
    "```\n",
    "\n",
    "and\n",
    "\n",
    "```python\n",
    "dataframe = country_footprints_by_product.transpose(copy=True)\n",
    "plot = dataframe.plot(kind='bar', stacked=True)\n",
    "plot.set_ylabel('tonnes CO2 per £')\n",
    "```\n",
    "\n",
    "and\n",
    "\n",
    "```python\n",
    "plots = country_footprints_by_product.plot(kind='barh', subplots=True)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 4.5 Calculating emissions by source industry and end product\n",
    "\n",
    "First make a new variable ```y_eagleton``` which extracts Eagleton's final demand column"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Do the same for Pawnee and make ```y_pawnee```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We now want to make two separate footprint result matrices. One for Eagleton and one for Pawnee. In each matrix, we want the columns to represent final products and the rows to be source industries.\n",
    "\n",
    "Using these matrices we can sum the columns to find the product footprints as shown in <b>Exercise 4.4</b>. But more interestingly, we can look at the composition of industries (and associated emissions) that are used to make a product.\n",
    "\n",
    "To do this, we will need to ensure that our multiplication gives a result of dimension $[6,6]$ \n",
    "\n",
    "The first matrix needs to be an 'industry by industry' matrix\n",
    "\n",
    "$\\textbf{L}$ is 'industry by product' matrix\n",
    "\n",
    "then the final matrix is a 'product by product' matrix\n",
    "\n",
    "The best way to do this is to diagonalise both ```e``` and ```y_eagleton```\n",
    "\n",
    "try: \n",
    "```python\n",
    "eagleton_footprint_full = np.dot(np.dot(np.diagflat(e.values), L), np.diag(y_eagleton))\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is actually a $[6,6]$ array of Eagleton's total footprint. The columns are the products and the rows are the breakdown of the supply chain - what industries are involved in making the product.\n",
    "\n",
    "You'll notice that you used ```np.diag(y_eagleton)``` rather than ```np.diagflat(y_eagleton)```. The reason for this is because when you select a single column from a matrix, python sees this as having zero width, just length and we have to use a different function. \n",
    "\n",
    "You'll also notice that we are refering to ```e.values``` before we diagonalise it. This is simply to make the calculation work with elements that are all arrays (rather than dataframes).\n",
    "\n",
    "It's annoying but the above code should work for you. \n",
    "\n",
    "Now make ```eagleton_footprint_full``` into a dataframe:\n",
    "\n",
    "```python\n",
    "eagleton_footprint_full = pd.DataFrame(eagleton_footprint_full, index=sectors, columns=sectors)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 4.6: What does this result matrix mean?\n",
    "\n",
    "What happens if you sum down the columns of ```eagleton_footprint_full```, remember to sum down the columns, use ```0``` as the dimension with ```np.sum```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Where have you seen these numbers before? Scroll up and check <b>Exercise 4.4</b>. You should notice that the column sum is the product footprint.\n",
    "\n",
    "Try \n",
    "```python\n",
    "eagleton_footprint_full.loc['Pawnee Energy','Eagleton Machines']\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This refers to the 124 tonnes of GHGs that are burnt making the Pawnee Energy that is part of the supply chain of the Eagleton Machines that are purchased as final demand by the people of Eagleton!\n",
    "\n",
    "Complicated?\n",
    "\n",
    "Yes\n",
    "\n",
    "Can you write a single line of code to make a dataframe of Pawnee's emissions by source industry and end product? Call the result ```pawnee_footprint_full```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What happens if you find the row sum of both ```eagleton_footprint_full``` and ```pawnee_footprint_full```? Try\n",
    "\n",
    "```python\n",
    "np.sum(eagleton_footprint_full,1)+np.sum(pawnee_footprint_full,1)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Do these numbers look familiar? \n",
    "\n",
    "You should find that this is our original $\\textbf{f}$ the vector of emissions from production. \n",
    "\n",
    "Production emissions get distributed across the rows. \n",
    "\n",
    "Or in other words, you can see the contribution that each industry makes to the production of each product (column)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercise 4.7: Graphing consumption emissions by source region\n",
    "\n",
    "Let's create a dataframe that tells us the emissions from Eagleton's consumption that are sourced domestically and those that are sourced from Pawnee. And the emissions from Pawnee's consumption that are sourced domestically and those that are sourced from Eagleton.\n",
    "\n",
    "Your finished table is going to look like this:\n",
    "\n",
    "<img src=\"https://github.com/earao/images/blob/main/Screenshot%202023-12-08%20at%2020.23.26.png?raw=true\" width=300 height=120 />\n",
    "\n",
    "First we make a $2$ by $2$ array of zeros to hold the data:\n",
    "\n",
    "```python\n",
    "data = np.zeros((2,2))\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now lets make our row headings:\n",
    "\n",
    "```python\n",
    "index = ['Eagleton CBA', 'Pawnee CBA']\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And the column headings:\n",
    "\n",
    "```python\n",
    "columns = ['domestic', 'imports']\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we sum the emissions from Eagleton' consumption that are sourced domestically and place this in the upper left cell of the data array. These are the emissions in ```eagleton_footprint_full``` that occur in the <b>rows</b> that represent Eagleton's industries. Try:\n",
    "\n",
    "```python\n",
    "data[0,0] = np.sum(np.sum(eagleton_footprint_full.loc['Eagleton Food':'Eagleton Energy',:],0),0)\n",
    "data\n",
    "```\n",
    "it's ok to have two lines of code in one box."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Can you write code for the top right to calculate the emissions from Eagleton's consumption that are imported?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now write two further lines of code to fill in the bottom row. Make sure the bottom left is the emissions sourced from Pawnee that are consumed by Pawnee! \n",
    "\n",
    "Remember to use your other 'footprint_full' dataframe for Pawnee's total footprint."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now put it all together in your dataframe. Call the dataframe ```all_data```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Make a stacked bar chart showing Eagleton and Pawnee's footprint by domestic and imported emissions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should have got a graph that looks like this:\n",
    "\n",
    "<img src=\"https://github.com/earao/images/blob/main/Screenshot%202023-12-08%20at%2020.23.45.png?raw=true\" width=500 height=400/>\n",
    "\n",
    "Can you see that Eagleton is reliant on imports, whereas Pawnee is a town which is more sufficient. Think about how you might expect the footprints of a developed versus developing country to look if you broke the emissions down by domestic and imports.\n",
    "\n",
    "## Key learning points\n",
    "\n",
    "You should have learnt:\n",
    "\n",
    "<ol>\n",
    "<li>How to make the individual matrix elements representing the transactions matrix, final demand and emissions</li>\n",
    "<li>How to make dataframes</li>\n",
    "<li>How to calculate e and L</li>\n",
    "<li>How to calculate total footprints, footprints by product and footprints by source industry and end product</li>\n",
    "<li>How to make bar charts and stacked bar charts of your results</li>\n",
    "   \n",
    "</ol>\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
